package com.mikao.config;


import com.mikao.dao.SysUserDao;
import com.mikao.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @author KennyDavid
 */

@Component
@Transactional(rollbackFor = Exception.class)
public class CustomerUserDetailsService implements UserDetailsService {

    private final SysUserDao sysUserDao;

    public CustomerUserDetailsService(SysUserDao sysUserDao) {
        this.sysUserDao = sysUserDao;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser sysUser = sysUserDao.findByAccountAndStatus(userName, true);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new UsernameNotFoundException(String.format("user %s does not exists", userName));
        }
        return new User(userName, sysUser.getPassword(), true, true, true, true, getAuthorities());
    }

    private Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return list;
    }
}
